package com.spring.tool;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Random;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.text.TextUtils;

/**
 * @purpose 工具类，提供一些公共方法
 * @author sudan
 */
public class Tools
{
	private static final String	TAG	= "Tools";

	/**
	 * @purpose 获取手机厂商和型号
	 * @return 手机厂商和型号
	 */
	public static String getModelInfo()
	{
		String strModelInfo = "";
		strModelInfo = Build.MANUFACTURER + "#" + Build.MODEL;
		return strModelInfo;
	}

	/**
	 * @purpose 获取系统版本
	 * @return 系统版本
	 */
	public static String getOSVersion()
	{
		String OSVersion = "";
		OSVersion = Build.VERSION.RELEASE;
		return OSVersion;

	}

	/**
	 * @purpose 获取软件版本
	 * @param context
	 *            上下文
	 * @return 软件版本
	 */
	public static String getAppVersionName(Context context)
	{
		String versionName = "";
		try
		{
			PackageManager pm = context.getPackageManager();
			PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
			versionName = pi.versionName;

			if (versionName == null || versionName.length() <= 0)
			{
				return "";
			}
		} catch (Exception e)
		{
//			WhtLog.e(TAG, "Exception", e);
		}
		return versionName;
	}

	/**
	 * 把字符串转化为整形的工具方法
	 * 
	 * @param str
	 * @param defaultValue
	 * @return
	 */
	public static int StringToInt(String str, int defaultValue)
	{
		int result = defaultValue;
		try
		{
			result = Integer.parseInt(str);
		} catch (Exception e)
		{
			e.printStackTrace();
		}
		return result;
	}

	public static float StringToFloat(String str, float defaultValue) {
		float result = defaultValue;
		try {
			result = Float.parseFloat(str);
		} catch (Exception e) {
			e.printStackTrace();
			result = defaultValue;
		}
		return result;
	}

	/**
	 * 0表示女 1表示男
	 */

	public static String number2sex(String number)
	{
		String sex = null;

		if (number != null)
		{
			if (number.equals("0"))
			{
				sex = "女";
			}
			else if (number.equals("1"))
			{
				sex = "男";
			}
		}
		return sex;
	}

	/**
	 * 截取后6位
	 * 
	 * @purpose
	 * @param number
	 * @return
	 */
	public static String get8number(String number){
		String new_number=null;
		if (number != null)
		{
			int len = number.length();
			new_number = number.substring(len - 8, len);
		}
		return new_number;

	}
	/**
     * 简体中文环境下的日期
     * 
     * @param timeMillis
     *            毫秒
     * @return String
     */
    public static String getDate_Zh_CN(long timeMillis)
    {
        String value = "";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        value = sdf.format(timeMillis);
        return value;
    }
    
	public static void getJsonString(String urlPath, Handler chargeHandler)
	{
		URL url;
		try
		{
			url = new URL(urlPath);
			HttpURLConnection connection = (HttpURLConnection) url
					.openConnection();
			connection.connect();
			InputStream inputStream = connection.getInputStream();
			// 对应的字符编码转换
			Reader reader = new InputStreamReader(inputStream, "UTF-8");
			BufferedReader bufferedReader = new BufferedReader(reader);
			String str = null;
			StringBuffer sb = new StringBuffer();
			while ((str = bufferedReader.readLine()) != null)
			{
				sb.append(str);
			}
//			WhtLog.d(TAG, "礼物计费鉴权返回---" + sb.toString());
			reader.close();
			connection.disconnect();
			JSONObject obj = new JSONObject(sb.toString());
//			WhtLog.d(TAG, "礼物计费鉴权json返回---" + obj);
			int code = obj.getInt("code");
			String msg = obj.getString("msg");
			Message giftMsg = new Message();
			Bundle bundle = new Bundle();
			bundle.putInt("code", code);
			bundle.putString("msg", msg);
			giftMsg.setData(bundle);
			giftMsg.what = 6001;
			chargeHandler.sendMessage(giftMsg);
		} catch (Exception e)
		{

			e.printStackTrace();
		}

	}
	/**
	 * 压缩图片
	 * */
	public static Bitmap getImageWHAdaptive(Bitmap bitmap, float sizeFlag) {

		Matrix matrix = new Matrix();
		int width = bitmap.getWidth();// 获取资源位图的宽
		int height = bitmap.getHeight();// 获取资源位图的高
		float bl = 1;
		if (width >= height) {
			bl = (float) sizeFlag;
		} else if (height > width) {
			bl = (float) sizeFlag;
		}
		matrix.postScale(bl, bl);
		// 根据缩放比例获取新的位图
		Bitmap newbmp = Bitmap.createBitmap(bitmap, 0, 0, width, height,
				matrix, true);
		return newbmp;
	}
	
	
	/**
	 * 得到　201310311242 年月日时分秒
	 * 
	 * @purpose
	 * @param time
	 * @return
	 */
	public static String getTimeDetail(long time)
	{
		String value = "";
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		value = sdf.format(time);
		return value;
	}
	
	public static String getBillCode(int feeCode){
		if(feeCode==1){
			return "1000000001";
		}else if(feeCode==2){
			return "1000000041";
		}
		return null;
	}
	
	/**
	 * 生成订单号   
	 *     时间戳+6位随机数
	 * @return
	 */
	public static String getOrderNumber() {
		StringBuffer buffer = new StringBuffer();
		buffer.append(System.currentTimeMillis());
		Random random = new Random();
		for (int i = 0; i < 6; i++) {
			buffer.append(random.nextInt(10));
		}
		return buffer.toString();
	}
	
	/**
	 * 获取当前的网络状态 -1：没有网络 1：WIFI网络2：wap网络3：net网络
	 * 
	 * @param context
	 * @return
	 */
	public static int getAPNType(Context context) {
		int netType = -1;
		ConnectivityManager connMgr = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
		if (networkInfo == null) {
			return netType;
		}
		int nType = networkInfo.getType();
		if (nType == ConnectivityManager.TYPE_MOBILE) {
			if (android.os.Build.VERSION.SDK_INT > 16) {// 测试发现android4.2.2启动必然崩溃,原因是最新版本android限制应用使用WRITE_APN_SETTINGS权限,所以判断一下,如果机器版本太高就跳过这里,6-24,liuy
				return 3;
			}
			// 增加电信网络判断
			Uri PREFERRED_APN_URI = Uri
					.parse("content://telephony/carriers/preferapn");
			final Cursor c = context.getContentResolver().query(
					PREFERRED_APN_URI, null, null, null, null);
			if (c != null) {
				c.moveToFirst();
				final String user = c.getString(c.getColumnIndex("user"));
				if (!TextUtils.isEmpty(user)) {
					if (user.contains("wap")) {
						netType = 2;
						c.close();
						return netType;
					} else {
						netType = 3;
						c.close();
						return netType;
					}
				}
			}
			c.close();
			if (networkInfo.getExtraInfo().toLowerCase().contains("net")) {
				netType = 3;
			} else {
				netType = 2;
			}
		} else if (nType == ConnectivityManager.TYPE_WIFI) {
			netType = 1;
		}
		return netType;
	}
	
	/**
	 * 判断手机SIM卡状态
	 * @param context
	 * @return ture:可用的   false ：不可用的
	 */
	public static boolean getSimCardState(Context context){
		boolean state = false;
		TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
		switch (telephonyManager.getSimState()) {
		case TelephonyManager.SIM_STATE_READY:
			state = true;
			break;
		case TelephonyManager.SIM_STATE_ABSENT:
			state = false;
			break;
		default:
			state = false;
			break;
		}
		return state;	
	}
}
